<template>
  <div class="box">
    <div class="list">
      <darkInput v-model="orig" size="small" title="起点" style="width: 300px" />
      <el-button type="primary" style="margin-left: 15px" @click="pickPoint(1)">图上选点</el-button>
    </div>
    <div class="list">
      <darkInput v-model="dest" title="终点" size="small" style="width: 300px" />
      <el-button type="primary" style="margin-left: 15px" @click="pickPoint(2)">图上选点</el-button>
    </div>
    <el-button type="primary" style="margin-top: 15px" @click="getLineG">开始导航</el-button>
    <el-button style="margin-top: 15px" @click="clear">清除导航路线</el-button>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue'
import { options_mark } from '../../../../js/test'
import { ElMessage } from 'element-plus'
import { createPoint } from '../../../../../api/gis3d/maputils'
import config from '../../../../../config/index'
const orig = ref(0)
const dest = ref(0)
const flag = ref(-1)
const getLineG = () => {
  if (orig.value <= 0 && dest.value <= 0) {
    return
  }
  const apiUrl = ` http://api.tianditu.gov.cn/drive?postStr={"orig":"${orig.value}","dest":"${dest.value}","style":"0"}&type=search&tk=${config.TDTTK}`
  fetch(apiUrl)
    .then((response) => response.text())
    .then((xmlString) => {
      // 使用DOMParser解析XML字符串
      const parser = new DOMParser()
      const xmlDoc = parser.parseFromString(xmlString, 'application/xml')
      const root = xmlDoc.documentElement
      const items = root.getElementsByTagName('routelatlon')
      let text = items[0].innerHTML

      text = text.split(';')
      text.pop()

      let pointArr = []
      for (const item of text) {
        var p = item.split(',')
        var arr = [p[0], p[1]]
        pointArr.push(arr)
      }
      setTimeout(() => {
        drawLine(pointArr)
      }, 1000)
    })
    .catch((error) => {
      ElMessage({
        message: error,
        type: 'error',
        plain: true
      })
    })
}
const drawLine = (data) => {
  // 初始化 Cesium Viewer

  // 假设data是你的路径数据，每个元素是一个包含经度和纬度的数组
  var positions = []
  for (const e of data) {
    positions.push(Cesium.Cartesian3.fromDegrees(e[0], e[1]))
  }

  // 计算中心点
  var centerCartesian = Cesium.Cartesian3.ZERO.clone()
  for (var i = 0; i < positions.length; i++) {
    centerCartesian = Cesium.Cartesian3.add(centerCartesian, positions[i], centerCartesian)
  }
  centerCartesian = Cesium.Cartesian3.divideByScalar(
    centerCartesian,
    positions.length,
    centerCartesian
  )

  // 转换为经纬度以便查看
  var centerCartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(centerCartesian)
  var centerLongitude = Cesium.Math.toDegrees(centerCartographic.longitude)
  var centerLatitude = Cesium.Math.toDegrees(centerCartographic.latitude)

  // 创建polyline实体
  let polyline_clampToGround_zindex0 = viewer.entities.add({
    name: 'polyline_clampToGround_zindex0',
    polyline: {
      show: true,
      positions: positions,
      width: 5,
      material: Cesium.Color.GREEN,
      clampToGround: true,
      zIndex: 0
    }
  })
  entityArr.push(polyline_clampToGround_zindex0)

  // 设置相机视角以查看整条线
  // 计算包围整个路径的矩形边界
  var boundingRectangle = Cesium.Rectangle.fromCartesianArray(positions)

  // 设置相机飞到这个边界
  viewer.camera.flyTo({
    destination: boundingRectangle,
    orientation: {
      heading: Cesium.Math.toRadians(centerLongitude), // 朝向中心点经度
      pitch: Cesium.Math.toRadians(-90), // 垂直向下看
      roll: 0
    }
  })

  // 或者，如果你想要更精确地控制视角高度，可以手动设置
  // var camera = viewer.camera;
  // var boundingSphere = Cesium.BoundingSphere.fromCartesianArray(positions);
  // var distance = camera.getFrustum().computePixelSize(boundingSphere.radius, viewer.scene.drawingBufferWidth, viewer.scene.drawingBufferHeight) * 10; // 乘以10是为了确保有足够的边距
  // viewer.camera.flyTo({
  //     destination: Cesium.Cartesian3.fromDegrees(centerLongitude, centerLatitude, boundingSphere.radius + distance),
  //     orientation: {
  //         heading: Cesium.Math.toRadians(centerLongitude),
  //         pitch: Cesium.Math.toRadians(-90 + Cesium.Math.toDegrees(distance / (boundingSphere.radius * 2))), // 根据距离调整俯仰角
  //         roll: 0
  //     }
  // });
}

const pickPoint = (i) => {
  flag.value = i
  if (i === 2 && orig.value <= 0) {
    ElMessage({
      message: '请先选择起点',
      type: 'warning',
      plain: true
    })
    return
  }
  openMousePick()
}
var handler
var entityArr = []
const openMousePick = () => {
  handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
  handler.setInputAction(function (evt) {
    // var cartesian=viewer.camera.pickEllipsoid(evt.position,viewer.scene.globe.ellipsoid);
    var ray = viewer.camera.getPickRay(evt.position)
    var position = viewer.scene.globe.pick(ray, viewer.scene)
    var cartographic = Cesium.Cartographic.fromCartesian(position)
    var lng = Cesium.Math.toDegrees(cartographic.longitude) //经度值
    var lat = Cesium.Math.toDegrees(cartographic.latitude) //纬度值

    if (flag.value === 1) {
      entityArr[0] && viewer.entities.remove(entityArr[0])
      orig.value = lng.toFixed(6) + ',' + lat.toFixed(6)
      entityArr.push(
        createPoint({ position: [lng, lat], url: '/static/icon/poi.png', label: { text: '起点' } })
      )
    } else {
      entityArr[1] && viewer.entities.remove(entityArr[1])
      dest.value = lng.toFixed(6) + ',' + lat.toFixed(6)
      entityArr.push(
        createPoint({ position: [lng, lat], url: '/static/icon/poi.png', label: { text: '终点' } })
      )
    }
    closehandler()
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

const closehandler = () => {
  handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

const clear = () => {
  for (const e of entityArr) {
    viewer.entities.remove(e)
  }
  orig.value = 0;
  dest.value = 0;
}

onUnmounted(() => {
  if (handler) closehandler()
})
</script>

<style lang="scss" scoped>
.box {
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  font-size: 18px;
  color: #fff;
  .list {
    display: flex;
    align-items: center;
    margin-top: 15px;
    font-size: 16px;
  }
}
</style>